//
//  OAloginViewController.m
//  WZEfengAndEtong
//
//  Created by wanzhao on 16/6/3.
//  Copyright © 2016年 wanzhao. All rights reserved.
//

#import "OAloginViewController.h"
#import "MBProgressHUD+WZ.h"
#import "NetWorkShare.h"
#import "WZOfficeController.h"
#import "WZOAoffice.h"
#import "MJExtension.h"
#import "NSDate+convenience.h"
#import "WZScheduleList.h"
#import "LocationNotification.h"

#define WZUserDefaults [NSUserDefaults standardUserDefaults]

#define OA_Info_OAUserName @"oaUserName"
#define OA_Info_OApassword @"oaUserId"
#define OA_Info_OAUserID @"oaUserId"
//#define OA_Info_OAUserID @"oaUserId"
//#define OA_Info_OAUserID @"oaUserId"
//#define OA_Info_OAUserID @"oaUserId"
//#define OA_Info_OAUserID @"oaUserId"
//#define OA_Info_OAUserID @"oaUserId"


#define LocalNotification_ScheduleTitle_KEY @"scheduleTitle"
#define LocalNotification_ScheduleID_KEY @"scheduleID"
#define LocalNotification_ScheduleStartTime_KEY @"scheduleStartTime"
#define LocalNotification_ScheduleStartDate_KEY @"scheduleStartDate"


@interface OAloginViewController ()<UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *userName;
@property (weak, nonatomic) IBOutlet UITextField *password;
@property (weak, nonatomic) IBOutlet UIButton *rmbBtn;

@property (nonatomic, strong) WZOAoffice *office;
@property (nonatomic, strong) NSMutableArray *scheduleArray;

@end

@implementation OAloginViewController

static NSString *comIDKey = @"comID";
static NSString *userIdKey = @"userID";
static NSString *nameKey = @"name";
static NSString *mailKey = @"mail";
static NSString *pwdKey = @"pwd";
static NSString *mobileKey = @"mobile";
static NSString *deptNameKey = @"deptName";
static NSString *rmbKey = @"rmb";


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
//    self.title = @"OA登录界面";
//    self.navigationController.navigationBar.backgroundColor = [UIColor whiteColor];
    
    [self setupUI];

}


- (void)setupUI {
    
    self.userName.delegate = self;
    self.password.delegate = self;
    
    NSString *oaAccount = [WZUserDefaults objectForKey:mailKey];
    NSString *pwd = [WZUserDefaults objectForKey:pwdKey];
    BOOL rmb = [WZUserDefaults boolForKey:rmbKey];
    if (rmb == YES) {
        _userName.text = oaAccount;
        _password.text = pwd;
    }
    
    _rmbBtn.selected = rmb;
//    isLoginOA = NO;
}


// 登录
- (IBAction)oaLoginBtnDidClick:(id)sender {
    
    [MBProgressHUD showMessage:@"登录办公系统..."];
    
    NSString *userName = [self.userName.text stringByReplacingOccurrencesOfString:@"@" withString:@"_"];
        
        [NetWorkShare loginOAWithUserName:userName pwd:self.password.text successHandle:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            if ([[responseObject objectForKey:@"success"] boolValue]) {
                
//                isLoginOA = YES;
                
                [MBProgressHUD hideHUD];
                // 字典转模型
                self.office = [WZOAoffice objectWithKeyValues:responseObject[@"userInfo"]];
                [self dataPersistent];
                
                [self registLocalNotificationOfeverySchedule:nil];
                
                [self checkMoblieAuthorize];
                
                [self dismissViewControllerAnimated:YES completion:nil];
                
            } else {
                [MBProgressHUD hideHUD];
                [MBProgressHUD showError:responseObject[@"message"]];
            }
            
        } failureHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
            
            [MBProgressHUD hideHUD];
            [MBProgressHUD showError:NETWORKNERROR];
            
            NSLog(@"error = %@", error);
        }];
}


#pragma mark - 创建通知

- (void)registLocalNotificationOfeverySchedule:(NSDate *)startDate {
    
    NSCalendar *greCalendar = [NSCalendar currentCalendar];
//    NSDateComponents *components = [greCalendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond fromDate:[NSDate date]];
//    [components setYear:startDate.year];
//    [components setMonth:startDate.month];
//    [components setDay:1];
//    [components setHour:0];
//    [components setMinute:0];
//    [components setSecond:0];
    
//    NSDate *beginDate = [greCalendar dateFromComponents:components];
    
    // 开始日期
    NSDate *beginDate = [NSDate dateWithTimeIntervalSinceNow:16 * 60];
    NSString *beginTime = [NSString stringWithFormat:@"%ld", [NSDate cTimestampFromDate:beginDate] * 1000];
    
    // 判断次月有几天
    NSRange range = [greCalendar rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:beginDate];
    
    NSDate *endDate = [beginDate dateByAddingTimeInterval:range.length * 24 * 3600 - 1];
    NSString *endTime = [NSString stringWithFormat:@"%ld", [NSDate cTimestampFromDate:endDate] * 1000];
    
    NSString *oaUserName = [[USER_DEFAULT objectForKey:@"oaUserName"] stringByReplacingOccurrencesOfString:@"@" withString:@"_"];
    NSString *oaPwd = [[USER_DEFAULT objectForKey:@"oaPwd"] md5String];
    [NetWorkShare queryScheduleWithUserName:oaUserName pwd:oaPwd beginTime:beginTime endTime:endTime alertBeginTime:nil alertEndTime:nil successHandle:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        if ([[responseObject objectForKey:@"success"] boolValue]) {
            [MBProgressHUD hideHUDForView:self.view];
            [self.scheduleArray removeAllObjects];
            self.scheduleArray = [WZScheduleList objectArrayWithKeyValuesArray:responseObject[@"rows"]];
            
            for (WZScheduleList *schedule in _scheduleArray) {
                
                // 如果是日程并没有注册通知
                if (schedule.typeFlag == 2) {
                    
                    // 获取线程中的提醒
                    NSArray *lns = [UIApplication sharedApplication].scheduledLocalNotifications;
                    for (UILocalNotification *ln in lns) {
                        NSString *scheduleTitle = ln.userInfo[LocalNotification_ScheduleTitle_KEY];
                        NSString *alertTime = ln.userInfo[LocalNotification_ScheduleStartTime_KEY];
                        NSString *scheduleID = ln.userInfo[LocalNotification_ScheduleID_KEY];
                        if (![schedule.title isEqualToString:scheduleTitle] && ![schedule.scheduleID isEqualToString:scheduleID]) {
                            // 提醒时间
                            NSString *alertTime = [NSString stringWithFormat:@"%lld", (schedule.startTime - 15 * 3600)];
                            NSDate *fireDate = [NSDate dateFromString:alertTime format:@"yyyy-MM-dd HH:mm"];
                            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                            [dict setObject:schedule.title forKey:LocalNotification_ScheduleTitle_KEY];
                            [dict setObject:[NSString stringWithFormat:@"%lld", schedule.startDate] forKey:LocalNotification_ScheduleStartDate_KEY];
                            [dict setObject:[NSString stringWithFormat:@"%lld", schedule.startTime] forKey:LocalNotification_ScheduleStartTime_KEY];
                            [dict setObject:schedule.scheduleID forKey:LocalNotification_ScheduleID_KEY];
                            
                            [LocationNotification registerLocalNotificationWithFireDate:fireDate repeatType:0 entity:dict];
                        }
                    }
                }
            }
            
        } else {
            [MBProgressHUD hideHUDForView:self.view];
            [MBProgressHUD showError:[responseObject objectForKey:@"message"] toView:self.view];
        }
        
    } failureHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [MBProgressHUD hideHUDForView:self.view];
        [MBProgressHUD showError:NETWORKNERROR toView:self.view];
    }];
    
}


// 获取指定时间点
- (NSDate *)creatCustomDateWithDate:(NSDate *)date Day:(NSInteger)day Hour:(NSInteger)hour Minute:(NSInteger)minute  {
    
    NSCalendar *greCalendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [greCalendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:[NSDate date]];
    [components setYear:date.year];
    [components setMonth:date.month];
    [components setDay:day];
    [components setHour:hour];
    [components setMinute:minute];
    
    NSDate *date1 = [greCalendar dateFromComponents:components];
    
    //    NSDate *endDate = [beginDate dateByAddingTimeInterval:24 * 3600 - 1];
    
    return date1;
}


#pragma mark - 数据持久化

- (void)dataPersistent {
    // 保存全局数据
    NSString *oaUserName = [self.userName.text stringByReplacingOccurrencesOfString:@"@" withString:@"_"];
    [USER_DEFAULT setObject:oaUserName forKey:@"oaUserName"];
    [USER_DEFAULT setObject:self.password.text forKey:@"oaPwd"];
    [USER_DEFAULT setObject:self.office.companyId forKey:@"oaCompanyID"];
    [USER_DEFAULT setObject:self.office.userId forKey:@"oaUserId"];
    [USER_DEFAULT setObject:self.office.mobile forKey:@"oaMobile"];
    [USER_DEFAULT setObject:self.office.mail forKey:@"oaMail"];
    [USER_DEFAULT setObject:self.office.name forKey:@"oaName"];
    [USER_DEFAULT setObject:self.office.deptName forKey:@"oaDeptName"];
    [USER_DEFAULT setObject:self.office.sex forKey:@"oaSex"];
    [USER_DEFAULT setObject:self.office.imageUrl forKey:@"oaImageUrl"];
    [USER_DEFAULT setObject:self.office.telePhone forKey:@"oatTelePhone"];
    [USER_DEFAULT setBool:self.rmbBtn.selected forKey:@"oaRmb"];
    [USER_DEFAULT synchronize];
    
    // 保存OA数据
    [WZUserDefaults setObject:self.userName.text forKey:mailKey];
    [WZUserDefaults setObject:self.password.text forKey:pwdKey];
    [WZUserDefaults setObject:self.office.companyId forKey:comIDKey];
    [WZUserDefaults setObject:self.office.userId forKey:userIdKey];
    [WZUserDefaults setObject:self.office.mobile forKey:mobileKey];
    [WZUserDefaults setObject:self.office.mail forKey:mailKey];
    [WZUserDefaults setObject:self.office.name forKey:nameKey];
    [WZUserDefaults setObject:self.office.deptName forKey:deptNameKey];
    [WZUserDefaults setBool:self.rmbBtn.selected forKey:rmbKey];
    [WZUserDefaults synchronize];

}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    [self dismissViewControllerAnimated:YES completion:nil];
    [self resignFirstResponder];
}

- (IBAction)savePwd:(UIButton *)sender {
    
    sender.selected = !sender.selected;

}


- (IBAction)forgetPwd:(id)sender {
    
    //
}

- (IBAction)backgroundTap:(id)sender {
    
    [self.view endEditing:YES];
    [_userName resignFirstResponder];
    [_password resignFirstResponder];

}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    
    [self.view endEditing:YES];
    [_userName resignFirstResponder];
    [_password resignFirstResponder];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [textField resignFirstResponder];
    return YES;
}


// 检查手机认证
- (void)checkMoblieAuthorize {
    
    
    NSString *oaUserId = [USER_DEFAULT objectForKey:@"oaUserId"];
    
    [NetWorkShare checkMobileWithUserId:oaUserId successHandle:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        [MBProgressHUD hideHUDForView:nil];
        
        NSString *mobileStr = @"";
        if (responseObject) {
            NSString *status =  [NSString stringWithFormat:@"%@",responseObject[@"status"]];
            if ([[responseObject objectForKey:@"success"] boolValue]) { // 0 代表没有认证
                
                if ([status isEqualToString:@"2"]) {
                    mobileStr = @"已认证";
                    WZLog(@"%@", mobileStr);
                } else {
                    
                }
                
            } else {
                
                if ([status isEqualToString:@"-1"]) {
                    
                    [MBProgressHUD showError:responseObject[@"message"]];
                    WZLog(@"没有对应的用户");
                } else if ([status isEqualToString:@"0"]) {
                    [MBProgressHUD showError:responseObject[@"message"]];
                    WZLog(@"手机未认证");
                } else if ([status isEqualToString:@"1"]) {
                    mobileStr = @"待审核";
                    WZLog(@"待审核");
                } else if ([status isEqualToString:@"3"]) {
                    mobileStr = @"审核被拒绝";
                    WZLog(@"审核被拒绝");
                }
                
            }
            
        } else {
            
        }
        
        [USER_DEFAULT setObject:mobileStr forKey:ISMOBILEAVALable];
        [USER_DEFAULT synchronize];
        
    } failureHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
        [MBProgressHUD hideHUDForView:nil];
        
    }];
}

- (NSMutableArray *)scheduleArray {
    if (!_scheduleArray) _scheduleArray = [[NSMutableArray alloc] init];
    return _scheduleArray;
}

@end
